"""游戏控制主模块"""
import board
import player
import random

from player import Player


class Game:
    """游戏类"""
    def __init__(self):
        self.chess_board = board.Board() #棋盘对象
        self.human = player.Player('玩家') #玩家对象
        self.computer = player.AIPlayer('电脑') #电脑玩家对象

    def random_player(self):
        """随机先手玩家"""

        #随机到1表示玩家先手
        if random.randint(0,1) ==1:
            _player = (self.human,self.computer)
        else:
            _player = (self.computer,self.human)

        _player[0].chess ='X'
        _player[1].chess ='O'

        print('根据随机结果 %s 先行' % _player[0].name)
        return _player
    def play_around(self):
        """一局游戏"""
        #显示棋盘
        self.chess_board.show_board(True)
        #决定先手玩家,元数组直接赋值给两个玩家变量
        current_player,next_player = self.random_player()

        while True:
            #下子方落子
            current_player.move(self.chess_board)
            #显示棋盘
            self.chess_board.show_board()
            #判断是否胜利
            if self.chess_board.is_win(current_player.chess):
                current_player.score +=1
                print('%s 战胜了 %s' % (current_player.name,next_player.name))
                break
            #是否是和局
            if self.chess_board.is_dogfall():
                print('%s 战成平局 %s' % (current_player.name, next_player.name))
                break

            #交换落子方
            current_player,next_player = next_player,current_player

        #显示比分
        print('[%s] 对战 [%s] 比分是: %d:%d'% (current_player.name,next_player.name,current_player.score,next_player.score))


    def start(self):
        """开启游戏，能够循环对局"""
        #开始游戏
        while True:
            #玩一局游戏
            self.play_around()

            #让用户选择是否再来一局
            is_contiune = input('是否再来一盘(Y/N):').upper()
            #判断是否要退出游戏
            if is_contiune != 'Y':
                break
            #重置棋盘数据
            self.chess_board.reset_board()



if __name__ == '__main__':
    game = Game()
    #测试先后手的分配结果
    #print(game.random_player()[0].name)

    #测试一局游戏
    #game.play_around()

    #测试循环对局
    game.start()